package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.util.Map;
import java.util.prefs.BackingStoreException;

@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求url
        String path = request.getRequestURI();
        if ("/customer/user/login".equals(path)){
            //放行
            return true;
        }
        //获取header的参数
        String token = request.getHeader("authorization");
        log.info("开始解析 customer user token:{}",token);
        if (ObjectUtil.isEmpty(token)){
            log.error("token不存在");
            //token失效
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        Map<String,Object> claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),token);
        log.info("claims:{}",claims);
        if (ObjectUtil.isEmpty(claims)){
            //token失效
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //存入当前请求的线程中
        UserThreadLocal.set(Long.valueOf(claims.get(Constants.JWT_USERID).toString()));
        UserThreadLocal.setSubject(claims.get(Constants.JWT_USERNAME).toString());
        //以上检查都没问题，一定返回true，这个请求才继续
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //响应结束，需要清理ThreadLocal中的数据，防止内存泄露
        UserThreadLocal.remove();
        UserThreadLocal.removeSubject();
    }
}
